'use strict';
const db = uniCloud.database();
const dbCmd = db.command;

exports.main = async (event, context) => {
  const { pk_id, user_id } = event;
  try {
    if (!pk_id || !user_id) {
      return { code: -1, msg: 'PK ID 或用户ID不能为空' };
    }

    const pkCollection = db.collection('pk_records');
    const userCollection = db.collection('users');

    const pkRes = await pkCollection.doc(pk_id).get();
    if (!pkRes.data.length) {
      return { code: -1, msg: 'PK记录不存在' };
    }
    const pk = pkRes.data[0];

    if (pk.challenger_id !== user_id && pk.opponent_id !== user_id) {
      return { code: -1, msg: '无权取消PK' };
    }

    if (pk.status === 'accepted') {
      // 比赛已开始，标记退出并结算
      await pkCollection.doc(pk_id).update({
        status: 'completed',
        exited_by: user_id,
        updated_at: new Date()
      });

      let challenger_points = pk.challenger_score || 0;
      let opponent_points = pk.opponent_score || 0;
      let winner_id = null;

      if (pk.challenger_answers.length && !pk.opponent_answers.length && user_id === pk.opponent_id) {
        winner_id = pk.challenger_id;
        challenger_points += 5;
      } else if (pk.opponent_answers.length && !pk.challenger_answers.length && user_id === pk.challenger_id) {
        winner_id = pk.opponent_id;
        opponent_points += 5;
      } else {
        if (pk.challenger_score > pk.opponent_score) {
          winner_id = pk.challenger_id;
          challenger_points += 5;
        } else if (pk.opponent_score > pk.challenger_score) {
          winner_id = pk.opponent_id;
          opponent_points += 5;
        } else {
          challenger_points += 2;
          opponent_points += 2;
        }
      }

      await userCollection.where({ _id: pk.challenger_id }).update({
        points: dbCmd.inc(challenger_points),
        updated_at: new Date()
      });
      if (pk.opponent_id) {
        await userCollection.where({ _id: pk.opponent_id }).update({
          points: dbCmd.inc(opponent_points),
          updated_at: new Date()
        });
      }

      await pkCollection.doc(pk_id).update({ winner_id });
    } else {
      await pkCollection.doc(pk_id).update({
        status: 'cancelled',
        updated_at: new Date()
      });
    }

    console.log('取消PK成功:', { pk_id, user_id }); // 调试
    return { code: 0, msg: '已取消PK' };
  } catch (e) {
    console.error('取消PK失败:', e);
    return { code: -1, msg: `取消PK失败: ${e.message || '未知错误'}` };
  }
};